package org.jetlinks.protocol.official.mqtt.down.zigbeeGateway.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.jetlinks.core.message.function.FunctionInvokeMessage;
import org.jetlinks.protocol.official.ObjectMappers;
import org.jetlinks.protocol.official.TopicPayload;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author bingzhong
 * @Date 2024/12/31 13:43
 * @Description ota 远程升级
 */
public class ZigbeeGatewayOTAUpgrade {

    static ObjectMapper mapper = ObjectMappers.JSON_MAPPER;

    @SneakyThrows
    public static TopicPayload encode(FunctionInvokeMessage functionInvokeMessage, String topicPatten) {

        String url = String.valueOf(functionInvokeMessage
                                              .getInput("url")
                                              .orElseThrow(() -> new IllegalArgumentException("url not exists")));

        String topic = String.valueOf(functionInvokeMessage
                                              .getInput("topic")
                                              .orElseThrow(() -> new IllegalArgumentException("topic not exists")));


        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("fid", "1");
        dataMap.put("object", "system");
        dataMap.put("method", "ota");
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("url", url);
        dataMap.put("param", paramMap);
        byte[] payloadBytes = mapper.writeValueAsBytes(dataMap);

        return TopicPayload.of(topic, payloadBytes);

    }

}
